/*
 * JBoss, Home of Professional Open Source
 * Copyright 2011, Red Hat, Inc. and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.mobicents.servlet.sip.example;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.sip.Address;
import javax.servlet.sip.Proxy;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipServletContextEvent;
import javax.servlet.sip.SipServletListener;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.URI;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;


public class CallBlockingSipServlet extends SipServlet implements SipServletListener {

	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(CallBlockingSipServlet.class);

    private static final String CONTACT_HEADER = "Contact";
    
    // adres + lokalizacja
    //static Map<String, URI> registeredUsers = null;
    static SipFactory sipFactory;
    private static final String CONTENT_TYPE = "text/plain;charset=UTF-8";

    /** Creates a new instance of CallBlockingSipServlet */
	public CallBlockingSipServlet() {}

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
			
        	BasicConfigurator.configure();
    		logger.debug("the call blocking sip servlet has been started");

    		super.init(servletConfig);	
            sipFactory =  (SipFactory)getServletContext().getAttribute(SIP_FACTORY);
            
            CDispatcher.getInstance();
            
        }

        @Override
        protected void doInvite(SipServletRequest request) throws ServletException, IOException {
        	
        	invite(request);
        	//sendMessage(request);
        }

        @Override
        protected void doRegister(SipServletRequest req) throws ServletException, IOException {
        	
	        	logger.debug("Received from: " + req.getFrom().toString());
	        	logger.debug(" register request: " + req.getTo().toString());
	           
	            int response = SipServletResponse.SC_OK;
                SipServletResponse resp = req.createResponse(response);
                                
                Address address = req.getAddressHeader(CONTACT_HEADER);
                String fromURI = req.getFrom().getURI().toString();
                
                int expires = address.getExpires();
                if(expires < 0) {
                        expires = req.getExpires();
                }
                if(expires == 0) {
                		AdressBook.removeCUser(fromURI);
                        logger.debug("User " + fromURI + " unregistered");
                        
                } else {
                        resp.setAddressHeader(CONTACT_HEADER, address);
                        AdressBook.addCUser(new CUser(fromURI, address.getURI()));
                        
                        logger.debug("User " + fromURI + " registered with an Expire time of " +  expires  + " and location: " + address.getURI());                  
                }                               
                                                
                resp.send();
        }
    
        @Override
        protected void doBye(SipServletRequest req) throws javax.servlet.ServletException, java.io.IOException
        {
        	 req.createResponse(SipServletResponse.SC_OK).send();
        }
        
        protected void doMessage(SipServletRequest request) throws ServletException, IOException 
        {
        	logger.debug("Got request: "+ request.toString());
    		String reqFromUri = request.getFrom().getURI().toString();
    		logger.debug(reqFromUri);
            
            String messageContent = "Serwer nie odpowiada na wiadomo�ci.";

            SipApplicationSession sipApplicationSession = sipFactory.createApplicationSession();
            SipURI fromURI = sipFactory.createSipURI("server", "main.com");
            URI receiverURI = request.getFrom().getURI();
            SipServletRequest sipServletRequest = sipFactory.createRequest(sipApplicationSession, "MESSAGE", fromURI, receiverURI);
            sipServletRequest.setContentLength(messageContent.length());
            sipServletRequest.setContent(messageContent, CONTENT_TYPE);
            sipServletRequest.setRequestURI(receiverURI);
            sipServletRequest.send();
        }
        
        public static void sendMessageToGroup(List<CUser> cUsers, String message)
        {
        	logger.debug("Got message to send : " + message);
    		
            String messageContent = message;

            SipApplicationSession sipApplicationSession = sipFactory.createApplicationSession();
            SipURI fromURI = sipFactory.createSipURI("server", "main.com");
            for (CUser cUser : cUsers) {
            	URI receiverURI = cUser.getLocationURI();
            	SipServletRequest sipServletRequest = sipFactory.createRequest(sipApplicationSession, "MESSAGE", fromURI, receiverURI);
                sipServletRequest.setContentLength(messageContent.length());
                try {
					sipServletRequest.setContent(messageContent, CONTENT_TYPE);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                sipServletRequest.setRequestURI(receiverURI);
                try {
					sipServletRequest.send();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
        }
        
        protected void invite(SipServletRequest request) throws ServletException, IOException 
        {
        	logger.debug("Got request: "+ request.toString());
    		String fromUri = request.getFrom().getURI().toString();
    		logger.debug(fromUri);
    		
			logger.debug(request.getRequestURI().toString() + " ze zbioru " + AdressBook.getList().size());
			URI contactAddresses = AdressBook.getCUser(request.getRequestURI().toString()).getLocationURI();
		    
            if(contactAddresses != null && contactAddresses.toString().length() > 0) {  
            		logger.debug("Proxy to: " + contactAddresses);
                    Proxy proxy = request.getProxy();
                    proxy.setRecordRoute(true);
                    proxy.setParallel(true);
                    proxy.setSupervised(false);
                    proxy.proxyTo(contactAddresses);                
            } 
            else {
                    logger.debug(request.getRequestURI().toString() + " is not currently registered");
                    
                    SipServletResponse sipServletResponse = request.createResponse(SipServletResponse.SC_MOVED_PERMANENTLY, "Moved Permanently");
                    sipServletResponse.send();
            }
    		
        }
        
		public void servletInitialized(SipServletContextEvent arg0) {
			logger.debug("the call blocking sip servlet has been initialized");
		}
	
}